package com.hnkywl.sts.service.cwgl;

import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.cwgl.*;
import com.hnkywl.sts.entity.cwgl.Fzhs;
import com.hnkywl.sts.entity.cwgl.Pzz;
import com.hnkywl.sts.entity.cwgl.Qtpz;
import com.hnkywl.sts.entity.cwgl.Qtpzfl;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-5-18
 * Time: 下午1:54
 * To change this template use File | Settings | File Templates.
 */
@Service
public class QtpzService {
    private QtpzDao qtpzDao;
    private QtpzflDao qtpzflDao;
    private PzzDao pzzDao;
    private FzhsDao fzhsDao;

    /**
     * 获取凭证字
     *
     * @return
     */
    public String findPzz() {
        List<Pzz> list = pzzDao.findAll();
        String json = BaseUtils.fetchCollectionToJson(list, "code", "name");
        return "[" + json + "]";
    }

    /**
     * 查询其他凭证
     *
     * @param status
     * @param saveStatus
     * @param startDate
     * @param endDate
     * @param companyId
     * @param no
     * @param voucherNo
     * @param createUser
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findQtpz(Integer status, Integer saveStatus, Date startDate, Date endDate, Long companyId, Long no, Integer voucherNo, String word, String createUser, Integer pageNo, Integer pageSize) {
        Page<Qtpz> page = qtpzDao.findQtpz(status, saveStatus, startDate, endDate, companyId, no, voucherNo, word, createUser, pageNo, pageSize);
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + new GsonBuilder().setDateFormat("yyyy-MM-dd").create().toJson(page.getResult()) + "}";
    }

    /**
     * 根据ID查找凭证
     *
     * @param id
     * @return
     */
    @Transactional
    public Qtpz findQtpz(Long id) {
        return qtpzDao.get(id);
    }

    /**
     * 凭证分录
     *
     * @param id
     * @return
     */
    @Transactional
    public String findQtpzfl(Long id) {
        List<String> list = new ArrayList<String>();
        Qtpz qtpz = qtpzDao.get(id);
        if (!CollectionUtils.isEmpty(qtpz.getQtpzflList()))
            for (Qtpzfl pzfl : qtpz.getQtpzflList()) {
                String temp = "\"zy\":\"" + (pzfl.getZy() == null ? "" : pzfl.getZy()) +
                        "\",\"kmdm\":\"" + (pzfl.getKmdm() == null ? "" : pzfl.getKmdm()) +
                        "\",\"kmmc\":\"" + (pzfl.getKmmc() == null ? "" : pzfl.getKmmc()) +
                        "\",\"jfje\":\"" + (pzfl.getJfje() == null ? "" : pzfl.getJfje()) +
                        "\",\"dfje\":\"" + (pzfl.getDfje() == null ? "" : pzfl.getDfje()) +
                        "\",\"fzhs\":\"" + (pzfl.getFzhs() == null ? "" : pzfl.getFzhs()) + "\"";
                if (!CollectionUtils.isEmpty(pzfl.getFzhsList()))
                    for (int i = 0; i < pzfl.getFzhsList().size(); i++) {
                        temp += ",\"fzhsList[" + i + "].type\":\"" + pzfl.getFzhsList().get(i).getType() +
                                "\",\"fzhsList[" + i + "].code\":\"" + pzfl.getFzhsList().get(i).getCode() +
                                "\",\"fzhsList[" + i + "].name\":\"" + pzfl.getFzhsList().get(i).getName() +
                                "\",\"fzhsList[" + i + "].qtpzfl.id\":\"" + pzfl.getFzhsList().get(i).getQtpzfl().getId() + "\"";
                    }
                temp = "{" + temp + "}";
                list.add(temp);
            }
        String json = StringUtils.join(list, ",");
        return "{\"total\":" + qtpz.getQtpzflList().size() + ",\"rows\":[" + json + "],\"footer\": [{\"zy\": \"合计\", \"jfje\": " + qtpz.getJfhj() + ", \"dfje\": " + qtpz.getDfhj() + "}]}";
    }

    /**
     * 保存其他凭证
     *
     * @param qtpz
     */
    @Transactional
    public void saveQtpz(Qtpz qtpz) {
        qtpz.setCreateUser(YgService.getCurrentYg());
        qtpz.setCreateOrgan(YgService.getCurrentYg().getZggs());
        qtpz.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        qtpz.setDateCreated(new Date());
        Date date = qtpz.getZdrq();
        GregorianCalendar gc = new GregorianCalendar();
        gc.setGregorianChange(date);
        qtpz.setAcctyear(gc.get(Calendar.YEAR));
        qtpzDao.save(qtpz);
    }

    /**
     * 更新其他凭证
     *
     * @param qtpz
     */
    @Transactional
    public void updateQtpz(Qtpz qtpz) {
        Qtpz clone = qtpzDao.get(qtpz.getId());
        if (!CollectionUtils.isEmpty(clone.getQtpzflList())) {
            for (Qtpzfl pzfl : clone.getQtpzflList()) {
                if (!CollectionUtils.isEmpty(pzfl.getFzhsList()))
                    for (Fzhs fzhs : pzfl.getFzhsList())
                        fzhsDao.delete(fzhs);
                qtpzflDao.delete(pzfl);
            }
        }
        clone = (Qtpz) ReflectionUtils.getInstance(clone, qtpz);
        clone.setLastUpdated(new Date());
    }

    /**
     * 删除其他凭证
     *
     * @param id
     */
    @Transactional
    public void deleteQtpz(Long id) {
        Qtpz qtpz = qtpzDao.get(id);
        qtpz.setLastUpdated(new Date());
        qtpz.setDeleted(1);
        for (Qtpzfl temp : qtpz.getQtpzflList()) {
            temp.setDeleted(1);
        }
    }

    /**
     * 复制其他凭证
     *
     * @param qtpz
     */
    @Transactional
    public void copyQtpz(Qtpz qtpz) {
        qtpz.setId(null);
        qtpz.setCreateUser(YgService.getCurrentYg());
        qtpz.setCreateOrgan(YgService.getCurrentYg().getZggs());
        qtpz.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        qtpz.setDateCreated(new Date());
        Date date = qtpz.getZdrq();
        GregorianCalendar gc = new GregorianCalendar();
        gc.setGregorianChange(date);
        qtpz.setAcctyear(gc.get(Calendar.YEAR));
        List<Qtpzfl> list = qtpz.getQtpzflList();
        for (Qtpzfl temp : list) {
            temp.setId(null);
        }
        qtpzDao.save(qtpz);
    }

    /**
     * 获取久其凭证分录信息
     *
     * @param id
     * @param uuid
     * @return
     */
    @Transactional
    public Map getVoucherItems(Long id, String uuid) {
        Map<String, Object> result = new HashMap<String, Object>();
        Qtpz temp = qtpzDao.get(id);
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        if (temp != null && !CollectionUtils.isEmpty(temp.getQtpzflList()))
            for (Qtpzfl item : temp.getQtpzflList()) {
                Map<String, Object> voucherItem = new HashMap<String, Object>();
                voucherItem.put("id", order);//唯一标识
                voucherItem.put("vchrid", uuid);//凭证主表ID
                voucherItem.put("itemorder", order);//分录编号
                voucherItem.put("subjectcode", item.getKmdm() != null && item.getKmdm() != null ? item.getKmdm() : "");//科目代码
                voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
                voucherItem.put("debit", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方金额
                voucherItem.put("credit", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方金额
                voucherItem.put("qty", item.getSl() != null ? item.getSl() : 0);//数量
                voucherItem.put("price", "0");//单价
                voucherItem.put("currencycode", "CNY");//货币代码
                voucherItem.put("exchrate", "1.000000");//汇率
                voucherItem.put("orgnd", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方原币
                voucherItem.put("orgnc", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方原币
                voucherItem.put("settlementcode", "");//结算方式代码
                voucherItem.put("settlementno", "");//结算号
                voucherItem.put("bizdate", temp.getZdrq() != null ? fmt.format(temp.getZdrq()) : "");//业务日期
                voucherItem.put("digest", item.getZy() != null ? item.getZy() : "");//摘要
                voucherItem.put("bizno", "");//业务号
                if (!CollectionUtils.isEmpty(item.getFzhsList()))
                    for (Fzhs fzhs : item.getFzhsList())
                        voucherItem.put(fzhs.getType(), fzhs.getCode());
                items.add(voucherItem);
                order++;
            }
        result.put("items", items);
        return result;
    }

    /**
     * 获取U8凭证分录信息
     *
     * @param id
     * @param uuid
     * @return
     */
    @Transactional
    public Map getU8VoucherItems(Long id, String uuid) {
        Map<String, Object> result = new HashMap<String, Object>();
        Qtpz temp = qtpzDao.get(id);
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        if (temp != null && !CollectionUtils.isEmpty(temp.getQtpzflList()))
            for (Qtpzfl item : temp.getQtpzflList()) {
                Map<String, Object> voucherItem = new HashMap<String, Object>();
                //voucherItem.put("id", order);//唯一标识
                //voucherItem.put("vchrid", uuid);//凭证主表ID
                voucherItem.put("entry_id", order);//分录编号
                voucherItem.put("account_code", item.getKmdm() != null && item.getKmdm() != null ? item.getKmdm() : "");//科目代码
//                voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
                voucherItem.put("natural_debit_currency", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方金额
                voucherItem.put("natural_credit_currency", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方金额
//                voucherItem.put("qty", item.getSl() != null ? item.getSl() : 0);//数量
                voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
                voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
                voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
                voucherItem.put("currency", "CNY");//货币代码
                voucherItem.put("exchange_rate2", "1.000000");//汇率
//                voucherItem.put("orgnd", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方原币
//                voucherItem.put("orgnc", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方原币
                voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
                voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
                voucherItem.put("document_date", temp.getZdrq() != null ? fmt.format(temp.getZdrq()) : "");//票据日期，在科目是银行或往来时，可以填写此项
                voucherItem.put("abstract", item.getZy() != null ? item.getZy() : "");//摘要
//                voucherItem.put("bizno", "");//业务号
                Map<String, String> fzhsMap = new HashMap<String, String>();
                Map<String, Map> xjllxmMap = new HashMap<String, Map>();
                if (!CollectionUtils.isEmpty(item.getFzhsList()))
                    for (Fzhs fzhs : item.getFzhsList()) {
                        if ("xjllxm".equals(fzhs.getType())) {
                            fzhsMap.put("item_id", fzhs.getCode());
                            Map value = new HashMap<String, Double>();
                            Double d = fzhs.getQtpzfl().getJfje() == null ? 0.0 : fzhs.getQtpzfl().getJfje();
                            Double c = fzhs.getQtpzfl().getDfje() == null ? 0.0 : fzhs.getQtpzfl().getDfje();
                            value.put("debit", d);
                            value.put("credit", c);
                            value.put("md", Math.abs(d - c));
                            value.put("ccode", item.getKmdm() != null && item.getKmdm() != null ? item.getKmdm() : "");
                            xjllxmMap.put(fzhs.getCode(), value);
                        } else if ("xm".equals(fzhs.getType())) {
                            fzhsMap.put("item_id", fzhs.getCode());
                        } else
                            fzhsMap.put(fzhs.getType(), fzhs.getCode());
                    }
                voucherItem.put("auxiliary_accounting", fzhsMap);
                voucherItem.put("cash_flow", xjllxmMap);
                items.add(voucherItem);
                order++;
            }
        result.put("items", items);
        return result;
    }

    /**
     * 取该凭证的表头
     *
     * @param id
     * @param uuid
     * @return
     */
    @Transactional
    public Map getVoucherMaster(Long id, String uuid) {
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        Qtpz result = qtpzDao.get(id);
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", result.getZh() != null ? result.getZh() : "");//凭证类别
        voucherMaster.put("acctyear", simpleDateFormat2.format(result.getZdrq()));//会计年度
        voucherMaster.put("acctperiod", simpleDateFormat3.format(result.getZdrq()));//会计期间
        voucherMaster.put("createdate", fmt.format(result.getZdrq()));//凭证日期
        voucherMaster.put("unitcode", result.getNbgs() != null && result.getNbgs().getJiuqiUnitCode() != null ? result.getNbgs().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("companyname", result.getNbgs() != null && result.getNbgs().getQc() != null ? result.getNbgs().getQc() : "");//公司名称
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", YgService.getCurrentYgName());//制单人
        voucherMaster.put("attachment", result.getFdjs() != null ? result.getFdjs() : "");//附件张数
        //voucherMaster.put("memo", result.getBz() != null ? result.getBz() : "");//备注
        return voucherMaster;
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Qtpz result = qtpzDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode", result.getNbgs().getJiuqiUnitCode());//单位代码
        revokeInfo.put("vchrtypecode", result.getZh());//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod", simpleDateFormat3.format(result.getZdrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号
        revokeInfo.put("memo", VoucherType.QTPZ.getTag()+id);//备注，在凭证删除时使用
        return revokeInfo;
    }

    @Autowired
    public void setQtpzDao(QtpzDao qtpzDao) {
        this.qtpzDao = qtpzDao;
    }

    @Autowired
    public void setQtpzflDao(QtpzflDao qtpzflDao) {
        this.qtpzflDao = qtpzflDao;
    }

    @Autowired
    public void setPzzDao(PzzDao pzzDao) {
        this.pzzDao = pzzDao;
    }

    @Autowired
    public void setFzhsDao(FzhsDao fzhsDao) {
        this.fzhsDao = fzhsDao;
    }
}
